# 分页对象
PageUtil = 

  # 计算总页数
  # count 总记录数
  # limit 每页条数
  getPageCount : (count, limit) ->
    pageCount = 0
    if 0 == count % limit
      pageCount = count / limit 
    else 
      pageCount = parseInt(count / limit, 10) + 1
    pageCount

  # 处理查询结果
  # limit 每页条数
  # pageNum 当前页码
  # count 总记录数
  # data 数据集
  handleResults : (limit, pageNum, count, data) ->
    results = {}
    results.pageSize = limit
    results.pageNum = pageNum
    results.pageCount = @getPageCount(count, limit)
    results.count = count
    results.data = data
    results

  # 查询记录数
  # model 模型对象
  # err 错误对象
  # limit 每页条数
  # pageNum 当前页号
  # data 数据集
  # cbf 回调函数
  doQuery : (model, conditions, err, limit, pageNum, data, cbf) ->
    if err
      return cbf err, null
    model.count conditions, (err, count) =>
      if err
        return cbf err, null
      results = @handleResults limit, pageNum, count, data
      cbf null, results

  # 分页查询
  # model 文档模型
  # conditions 查询条件
  # sorts 排序
  # pageSize 每页显示记录数
  # pageNum 当前页码
  pageQuery : (model, conditions, sorts, pageSize, pageNum, cbf) ->
    @pageQuery2 model, conditions, null, sorts, pageSize, pageNum, cbf

  # 分页查询, 指定字段
  # model 文档模型
  # conditions 查询条件
  # fields 要查询的字段
  # sorts 排序
  # pageSize 每页显示记录数
  # pageNum 当前页码
  # cbf 回调函数
  pageQuery2 : (model, conditions, fields, sorts, pageSize, pageNum, cbf) ->
    if isNaN pageSize
      pageSize = 10

    if isNaN pageNum
      pageNum = 1

    pageSize = parseInt pageSize, 10
    pageNum = parseInt pageNum, 10

    limit = pageSize ? 10
    newPageNum = pageNum ? 1
    skip = (newPageNum - 1) * pageSize

    if fields
      model.find(conditions, fields).sort(sorts).limit(limit).skip(skip).exec (err, data) =>
        @doQuery model, conditions, err, limit, newPageNum, data, cbf
    else
      model.find(conditions).sort(sorts).limit(limit).skip(skip).exec (err, data) =>
        @doQuery model, conditions, err, limit, newPageNum, data, cbf

  # 构造分页结果
  # items 数据集
  # pageNum 当前页码
  # pageSize 每页显示记录数
  pagination : (items, pageNum, pageSize) ->
    pageCount = Math.ceil(items.length / pageSize)  # assert pageSize > 0
    results =
      pageNum: pageNum
      pageSize: pageSize
      pageCount: pageCount
      count: items?.length || 0
      data: items?.slice (pageNum-1)*pageSize, (pageNum)*pageSize
    return results
    
module.exports = PageUtil